package home.contaduria.web;

import home.contaduria.domain.Expense;
import home.contaduria.domain.ExpenseType;
import home.contaduria.domain.Income;
import home.contaduria.domain.IncomeType;

import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.support.FormattingConversionServiceFactoryBean;

/**
 * A central place to register application Converters and Formatters.
 */
public class ApplicationConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean {

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        installLabelConverters(getObject());
    }

    private void installLabelConverters(FormatterRegistry registry) {
        registry.addConverter(new ExpenseConverter());
        registry.addConverter(new IncomeConverter());
        registry.addConverter(new ExpenseTypeToStringConverter());
        registry.addConverter(new StringToExpenseTypeConverter());
        registry.addConverter(new IncomeTypeToStringConverter());
        registry.addConverter(new StringToIncomeTypeConverter());
    }

    static class ExpenseConverter implements Converter<Expense, String> {
        public String convert(Expense expense) {
            return new StringBuilder().append(expense.getId()).append(" ").append(expense.getOperationDate()).append(" ")
                    .append(expense.getOperationSum()).append(" ").append(expense.getVersion()).toString();
        }

    }

    static class IncomeConverter implements Converter<Income, String> {
        public String convert(Income income) {
            return new StringBuilder().append(income.getOperationDate()).append(" ").append(income.getOperationSum()).toString();
        }

    }

    static class ExpenseTypeToStringConverter implements Converter<ExpenseType, String> {
        @Override
        public String convert(ExpenseType source) {
            return source.getName();
        }

    }

    static class StringToExpenseTypeConverter implements Converter<String, ExpenseType> {

        @Override
        public ExpenseType convert(String source) {
            ExpenseType expenseType = new ExpenseType();
            expenseType.setName(source);
            return expenseType;
        }

    }

    static class IncomeTypeToStringConverter implements Converter<IncomeType, String> {

        @Override
        public String convert(IncomeType source) {
            return source.getName();
        }

    }

    static class StringToIncomeTypeConverter implements Converter<String, IncomeType> {

        @Override
        public IncomeType convert(String source) {
            IncomeType incomeType = new IncomeType();
            incomeType.setName(source);
            return incomeType;
        }

    }

}
